# -*- coding: utf-8 -*-
"""
通知系统 - 视图函数
"""

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from .models import Notification
from django.utils import timezone


@login_required
def notification_list(request):
    """通知列表页面"""
    return render(request, 'notifications/list.html')


# ========== API视图 ==========

@login_required
@require_http_methods(["GET"])
def api_notifications_list(request):
    """获取通知列表API"""
    notifications = Notification.objects.filter(user=request.user).order_by('-created_at')
    
    # 类型筛选
    notification_type = request.GET.get('type')
    if notification_type and notification_type != 'unread':
        notifications = notifications.filter(type=notification_type)
    
    # 未读筛选
    if notification_type == 'unread':
        notifications = notifications.filter(is_read=False)
    
    # 分页
    page = int(request.GET.get('page', 1))
    page_size = int(request.GET.get('page_size', 20))
    
    start = (page - 1) * page_size
    end = start + page_size
    total = notifications.count()
    
    results = [{
        'id': n.id,
        'type': n.type,
        'type_display': n.get_type_display(),
        'title': n.title,
        'content': n.content,
        'is_read': n.is_read,
        'link_url': n.link_url,
        'created_at': n.created_at.isoformat(),
    } for n in notifications[start:end]]
    
    return JsonResponse({
        'code': 200,
        'data': {
            'results': results,
            'count': total,
            'page': page,
        }
    })


@login_required
@require_http_methods(["POST"])
def api_mark_as_read(request, notification_id):
    """标记通知为已读API"""
    try:
        notification = Notification.objects.get(id=notification_id, user=request.user)
        notification.is_read = True
        notification.read_at = timezone.now()
        notification.save(update_fields=['is_read', 'read_at'])
        
        return JsonResponse({
            'code': 200,
            'message': '已标记为已读'
        })
    except Notification.DoesNotExist:
        return JsonResponse({
            'code': 404,
            'message': '通知不存在'
        }, status=404)


@login_required
@require_http_methods(["POST"])
def api_mark_all_as_read(request):
    """全部标记为已读API"""
    Notification.objects.filter(user=request.user, is_read=False).update(
        is_read=True,
        read_at=timezone.now()
    )
    
    return JsonResponse({
        'code': 200,
        'message': '已全部标记为已读'
    })


@login_required
@require_http_methods(["GET"])
def api_unread_count(request):
    """获取未读通知数量API"""
    count = Notification.objects.filter(user=request.user, is_read=False).count()
    
    return JsonResponse({
        'code': 200,
        'data': {
            'count': count
        }
    })
